package jp.co.systemi.asp.workflow.apply;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Logger;

import jp.co.systemi.asp.workflow.Main;
import jp.co.systemi.asp.workflow.data.Apply;
import jp.co.systemi.asp.workflow.data.Common;
import jp.co.systemi.asp.workflow.data.PaidHoliday;
import jp.co.systemi.asp.workflow.data.PaidHolidayMeta;
import jp.co.systemi.asp.workflow.peer.ApplyPeer;
import jp.co.systemi.asp.workflow.peer.PaidHolidayPeer;

import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.ajax.markup.html.AjaxLink;
import org.apache.wicket.markup.html.WebMarkupContainer;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.list.ListItem;
import org.apache.wicket.markup.html.list.ListView;
import org.apache.wicket.model.PropertyModel;
import org.slim3.datastore.Datastore;

import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;

public class PaidHolidayRef extends Main {
    /**
     * ログ出力 クラス名をあわせること
     */
    @SuppressWarnings("unused")
    private static final Logger log = Logger.getLogger(PaidHolidayRef.class
            .getName());
    public static final String CATEGORY = "有給休暇";
    List<PaidHoliday> holidays = new ArrayList<PaidHoliday>(); // 申請分または承認済みがまだ未消化（日付が過ぎてない）有給休暇一覧
    List<Apply> approvers = new ArrayList<Apply>(); // 承認者および承認状況
    PaidHoliday master = null;

    WebMarkupContainer tblApprovers = new WebMarkupContainer("wi_tblApprover");

    /**
     * コンストラクター 画面の生成、イベント処理の定義はすべて、この中で完結する
     */
    public PaidHolidayRef() {
        init();
    }

    private void init() {
        // データストアーから初期化する入力項目の生成は一番先に行う
        UserService userService = UserServiceFactory.getUserService();

        com.google.appengine.api.users.User usr = userService.getCurrentUser();
        String loginId = usr.getEmail();
        // マスタデータ
        PaidHolidayMeta phm = PaidHolidayMeta.get();
        List<PaidHoliday> masters = Datastore.query(phm).filter(
                phm.loginId.equal(loginId),
                phm.status.equal(Common.APPLY_STATUS.MASTER)).asList();
        if (masters.size() == 0) {
            // マスタデータを作成する
            master = new PaidHoliday();
            master.setLoginId(loginId);
            master.setStatus(Common.APPLY_STATUS.MASTER);
            master.setRemainingDays(0.0); // デフォルト０
            Datastore.put(master);
        } else {
            master = masters.get(0);
        }

        // 申請中、または承認済みがまだ未消化（日付が過ぎてない）有給休暇一覧を取得
        List<PaidHoliday> holidayData = PaidHolidayPeer.getHolidays(loginId);
        if (holidayData == null) {
            error(getString("data.error"));
            return;
        }
        holidays.addAll(holidayData);
        // Formを生成する
        final Form<PaidHolidayRef> form = new MainForm<PaidHolidayRef>(this,
                "wi_refPaidHolidayForm");
        // 有給休暇リスト
        final WebMarkupContainer tblHoliday = new WebMarkupContainer(
                "wi_tblPaidHoliday");
        tblHoliday.setOutputMarkupId(true);
        form.add(tblHoliday);
        tblHoliday.add(new ListView<PaidHoliday>("wi_trPaidHoliday", holidays) {
            private static final long serialVersionUID = 4846361379394092695L;

            @Override
            protected void populateItem(ListItem<PaidHoliday> item) {
                final PaidHoliday holiday = item.getModelObject();
                SimpleDateFormat sdf = new SimpleDateFormat(
                        getString("date.format"));
                item.add(new Label("wi_tdSeq", new PropertyModel<Integer>(
                        holiday, "seq")));
                AjaxLink<Object> tdLink = new AjaxLink<Object>(
                        "wi_tdLink2Approver") {
                    private static final long serialVersionUID = 1L;

                    @Override
                    public void onClick(AjaxRequestTarget target) {
                        approvers.clear();
                        List<Apply> applies = ApplyPeer.getApplies(holiday.getApplyId());
                        if(applies == null){
                            error(getString("data.error"));
                            target.addComponent(feedback);
                            return;
                        }
                        approvers.addAll(applies);
                        tblApprovers.setVisible(true);
                        target.addComponent(tblApprovers);
                    }

                };
                item.add(tdLink);
                tdLink.add(new Label("wi_tdApplyNo", new PropertyModel<Long>(
                        holiday, "applyId.id")));
                item.add(new Label("wi_tdStartDate", sdf.format(holiday
                        .getStartDate())));
                item.add(new Label("wi_tdEndDate", sdf.format(holiday
                        .getEndDate())));
                item.add(new Label("wi_tdDays", new PropertyModel<Double>(
                        holiday, "days")));
                item.add(new Label("wi_tdMemo", new PropertyModel<String>(
                        holiday, "memo")));
                item.add(new Label("wi_tdStatus", new PropertyModel<String>(
                        holiday, "status")));
            }
        });
        form.add(new Label("wi_remainingDays", new PropertyModel<Double>(
                master, "remainingDays")));
        form.add(tblApprovers);
        tblApprovers.add(new ListView<Apply>("wi_trApprover", approvers) {
            private static final long serialVersionUID = 1L;

            @Override
            protected void populateItem(ListItem<Apply> item) {
                Apply user = (Apply) item.getModelObject();
                item.add(new Label("wi_tdApproverSeq",
                        new PropertyModel<String>(user, "seq")));
                item.add(new Label("wi_tdApproverRole",
                        new PropertyModel<String>(user, "role")));
                item.add(new Label("wi_tdApproverUserName",
                        new PropertyModel<String>(user, "approverName")));
                item.add(new Label("wi_tdApproverGroupName",
                        new PropertyModel<String>(user, "approverGroupName")));
                item.add(new Label("wi_tdApproverMemo",
                        new PropertyModel<String>(user, "memo")));
                item.add(new Label("wi_tdApproverStatus",
                        new PropertyModel<String>(user, "status")));

            }

        });
        tblApprovers.setOutputMarkupId(true);
        // tblApprovers.setVisible(false);
    }

}
